var basePath = $("#basePath").val();
$(document).ready(function (){
    menuCss("经销商");
    bindEvent();
    querySupplierList(0,10);
    var url = basePath + "/base/queryProvince";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            initQueryData(data.data);
        }else {
            flavrShowByTime(data.msg,null,"danger",false);
            return;
        }
    });

    $("#queryForm").find("[name='cityId']").val(null);
    $("#queryForm").find("[name='cityId']").select2({
        language: 'zh-CN',
        placeholder: '请选择城市',
        allowClear: true});
    $("#queryForm").find("[name='areaId']").val(null);
    $("#queryForm").find("[name='areaId']").select2({
        language: 'zh-CN',
        placeholder: '请选择区域',
        allowClear: true});

    $("#show-count").change(function(){
        querySupplierList(0,$("#show-count").val());
    });

    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
});

function initQueryData(object){
    var province = $("#queryForm").find("[name='provinceId']");
    $(province).html("");
    var html = "";
    $.each(object,function (index,item) {
        html += "<option value='"+item.provinceId+"'>"+item.province+"</option>"
    });
    $(province).html(html);
    $(province).val(null);
    $(province).select2({language: 'zh-CN',placeholder: "请选择省份",allowClear: true});
}

//绑定事件
function bindEvent(){
        $("#add").click(function (){
            initAddSupplierData();
            $("#add-modal").iziModal("open",this);
        });

        $("#saveSupplier").click(function (){
            saveSupplier();
        });

        $("#edit").click(function (){
            initAddSupplierData();
            editSupplierInitData();
        });

        $("#search").click(function (){
            querySupplierList(0,10);
        });
}


$("#add-modal").iziModal({
    title: "编辑经销商",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1042,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    onOpening: function () {
        //initAddHospitalData();
        validator();
    },
    onOpened: function () {
    },
    onClosing: function () {
    },
    onClosed: function () {
        $("#add-update-from").find("[name='maintainer']").val(null);
        $('#add-update-from')[0].reset();
        $("#add-update-from").find("[name='cityId']").html("");
        $("#add-update-from").find("[name='areaId']").html("");
        $("#add-update-from").data('bootstrapValidator').destroy();

    }
});

//表单校验
function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            supplierName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },supplierNo:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }
        }
    });
}

//新增供应商初始化数据
function initAddSupplierData(){
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    var province = $("#add-update-from").find("[name='provinceId']");
    var city = $("#add-update-from").find("[name='cityId']");
    var area = $("#add-update-from").find("[name='areaId']");

    $(province).html($("#queryForm").find("[name='provinceId']").html());
    $(province).val(null);

    $("#add-update-from").find("[name='provinceId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
    $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
    $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});


    $(province).change(function (){
        provinceChang(null,function (){
            $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        });
    });

    $(city).change(function (){
        cityChang(null,function (){
            $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        });
    });
}
//绑定省份值改变事件
function provinceChang(cityId,fn){
    var value = $("#add-update-from").find("[name='provinceId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='cityId']").html("");
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryCity";
    publicAjax(url,"POST",{"provinceId":value},function (data) {
        $("#add-update-from").find("[name='cityId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.cityId == cityId){
                html += "<option value='"+item.cityId+"' selected>"+item.city+"</option>"
            }else{
                html += "<option value='"+item.cityId+"'>"+item.city+"</option>"
            }

        });
        $("#add-update-from").find("[name='cityId']").html(html);
        $("#add-update-from").find("[name='cityId']").val(null);
        fn();
    })

}
//绑定城市值改变事件
function cityChang(areaId,fn){
    var value = $("#add-update-from").find("[name='cityId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryArea";
    publicAjax(url,"POST",{"cityId":value},function (data) {
        $("#add-update-from").find("[name='areaId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.areaId == areaId){
                html += "<option value='"+item.areaId+"' selected>"+item.area+"</option>"
            }else{
                html += "<option value='"+item.areaId+"'>"+item.area+"</option>"
            }
        });
        $("#add-update-from").find("[name='areaId']").html(html);
        $("#add-update-from").find("[name='areaId']").val(null);
        fn();
    })
}


function querySupplierList(start,end){
    var json = {};
    json.start = start;
    json.end = $("#show-count").val();
    json.allName = $("#queryForm").find("[name='allName']").val();
    json.provinceId = $("#queryForm").find("[name='provinceId']").val();
    json.cityId = $("#queryForm").find("[name='cityId']").val();
    json.areaId = $("#queryForm").find("[name='areaId']").val();

    var url = basePath + "/supplier/querySupplierList";
    publicAjax(url,"POST",json,function (data) {
            if(data.ret == 200){
                bindSupplierData(data.data.list);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
    });
}

function bindSupplierData(obj){
        $("#supplier_table").html("");
        var html = "";
        if(obj == null || obj.length == 0){
            html = "<tr><td class='text-center' colspan='12'>暂无数据</td></tr>";
        }else{
            $.each(obj,function (index,item){
                var manufacturerName = '';
                if(item.manufacturerName != null && item.manufacturerName  != ''){
                    manufacturerName = item.manufacturerName+"..."
                }
                html+= "<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
                    "<td class='text-center text-muted'><input type='checkbox' class='flat-green' name='one' value='"+item.supplierId+"'></td>" +
                    "<td class='text-center text-muted'>"+(item.supplierName==null?'' : item.supplierName )+"</td>" +
                    "<td class='text-center text-muted'>"+(item.supplierNo==null?'' : item.supplierNo )+"</td>" +
                    "<td class='text-center text-muted'>"+(item.region==null?'' : item.region )+"</td>" +
                    "<td class='text-center text-muted'>"+(item.supplierContacts==null?'' : item.supplierContacts )+"</td>" +
                    "<td class='text-center text-muted'>"+(item.supplierPhone==null?'' : item.supplierPhone )+"</td>" +
                    "<td class='text-muted'><a href='javascript:showManufacturer("+item.supplierId+")'>" + (manufacturerName)+ "</a></td>" +
                    "<td class='text-center text-muted'>"+(item.address==null?'' : item.address )+"</td>" +
                    "</tr>";
            });
        }
    $("#supplier_table").html(html);
    initDomCss();
}

function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}

var bl = false;
function saveSupplier(){
    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl){
            bl = true;
            var url = basePath+"/supplier/addOrUpdateSupplier";
            publicAjax(url,"POST",$("#add-update-from"),function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    querySupplierList(0,10);
                    $("#add-modal").iziModal("close",this);
                    bl = false;
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    bl= false;
                }
            })
        }
    }
}


function editSupplierInitData(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个经销商", null, "danger", false);
        return;
    }
    var json = {"supplierId":$("input[name='one']:checked").val()};
    var url=basePath+"/supplier/querySupplierInfo";
    publicAjax(url,"POST",json,function (data) {
        bindSupplierInfo(data.data);
    });
}

function bindSupplierInfo(obj) {
        $("#add-update-from").find("[name='supplierId']").val(obj.supplierId);
        $("#add-update-from").find("[name='supplierName']").val(obj.supplierName == null ? '' : obj.supplierName);
        $("#add-update-from").find("[name='supplierNo']").val(obj.supplierNo == null ? '' : obj.supplierNo);
        $("#add-update-from").find("[name='address']").val(obj.address == null ? '' : obj.address);
        $("#add-update-from").find("[name='supplierContacts']").val(obj.supplierContacts == null ? '' : obj.supplierContacts);
        $("#add-update-from").find("[name='supplierPhone']").val(obj.supplierPhone == null ? '' : obj.supplierPhone);
        $("#add-update-from").find("[name='remark']").val(obj.remark == null ? '' : obj.remark);

    if(obj.provinceId != null){
        $("#add-update-from").find("[name='provinceId']").val(obj.provinceId);
        showText($("#add-update-from").find("[name='provinceId']"));
    }

    provinceChang(obj.cityId,function (){
        $("#add-update-from").find("[name='cityId']").val(obj.cityId);
        showText( $("#add-update-from").find("[name='cityId']"));

        cityChang(obj.areaId,function (){
            $("#add-update-from").find("[name='areaId']").val(obj.areaId).change();
            showText( $("#add-update-from").find("[name='areaId']"));
        });
    });

    $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").attr("checked",true);
    $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").addClass("checked");
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    $("#add-modal").iziModal("open",this);
}

function showText(obj){
    var text2 =$(obj).find("option:selected").text();
    $(obj).select2({language:'zh-CN', placeholder:text2, allowClear:true});
}


function showManufacturer(id){
    var url = basePath+"/manufacturer/queryManufacturerListBySuppId";
    publicAjax(url,"POST",{supplierId:id},function (data){
        if(data.ret == 200){
            bindManufacturerListData(data.data);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}



function bindManufacturerListData(obj){
    $("#manufacturer_list").html("");
    if(obj == null || obj.length == 0){
        $("#manufacturer_list").html("<tr><td colspan='8' class='text-muted text-center'>暂无厂商信息</td></tr>");
    }else{
        var html = "";
        $.each(obj,function (index,item) {
            html+="<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerNo==null?'':item.manufacturerNo)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerName==null?'':item.manufacturerName)+"</td>" +
                "<td class='text-center text-muted'>"+(item.shortName==null?'':item.shortName)+"</td>" +
                "<td class='text-center text-muted'>"+(item.region==null?'':item.region)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerContacts==null?'':item.manufacturerContacts)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerPhone==null?'':item.manufacturerPhone)+"</td>" +
                "</tr>"
        });
        $("#manufacturer_list").html(html);
    }
    $("#manufacturer_modal").iziModal("open",this);
}



$("#manufacturer_modal").iziModal({
    title: "厂商信息",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1000,
    zindex: 1042,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    onOpening: function () {
    },
    onOpened: function () {
    },
    onClosing: function () {
    },
    onClosed: function () {

    }
});